<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 消息提示框 -->
      <el-alert title="添加商品信息" type="info" center show-icon></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeStep-0" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏选项 -->
      <el-form
        :model="addForm"
        :rules="rules"
        ref="addForm"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <el-tabs
          :tab-position="tabPosition"
          v-model="activeStep"
          @tab-click="tabClick"
          :before-leave="beforeLeave"
        >
          <el-tab-pane label="基本信息" name="0">
            <!-- 基本信息栏 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择器 -->
              <el-cascader
                :props="cascaderCate"
                clearable
                v-model="selc_cateID"
                :options="CateList"
                expand-trigger="hover"
                @change="CateChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in goodsParams" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(item1,i) in item.attr_vals" :key="i" :label="item1" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in goodsAttr" :key="item.attr_id">
              <el-input v-model="item.attr_vals" :value="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :headers="resquireHeader"
              :on-success="updateOK"
              :file-list="fileList"
              list-type="picture"
              :on-remove="removeFile"
              :on-preview="previewPic"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor id="editor" v-model.trim="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addGoodsBtn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" width="30%" :visible.sync="previewVisible" :before-close="previewClose">
      <img :src="previewPath" alt class="preimg" />
    </el-dialog>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

export default {
  data() {
    return {
      previewVisible: false,
      tabPosition: 'left',
      activeStep: '0',
      addForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: '',
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      rules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          {
            min: 1,
            max: 7,
            message: '最少1块起~最多不能大100万',
            trigger: 'blur'
          }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { min: 1, max: 7, message: '请输入正确的重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { min: 1, max: 7, message: '请输入正确的数量', trigger: 'blur' }
        ]
      },
      selc_cateID: [],
      CateList: [],
      cascaderCate: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      goodsParams: [],
      goodsAttr: [],
      fileList: [],
      resquireHeader: {
        Authorization: window.sessionStorage.getItem('token')
      },
      previewPath: ''
    }
  },
  methods: {
    // 获取分类数据的函数
    async getCateList() {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200)
        return this.$message.error('获取分类列表失败~')
      this.CateList = res.data
    },
    // tab标签切换时触发的函数
    async tabClick() {
      if (this.activeStep === '1') {
        const { data: res } = await this.$http.get(
          'categories/' +
            this.selc_cateID[this.selc_cateID.length - 1] +
            '/attributes',
          { params: { sel: 'many' } }
        )
        if (res.meta.status !== 200)
          return this.$message.error('获取商品参数失败~')
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.split(' ')
        })
        this.goodsParams = res.data
      }
      if (this.activeStep === '2') {
        const { data: res } = await this.$http.get(
          'categories/' +
            this.selc_cateID[this.selc_cateID.length - 1] +
            '/attributes',
          { params: { sel: 'only' } }
        )
        if (res.meta.status !== 200)
          return this.$message.error('获取商品属性失败~')
        // res.data.forEach(item => {
        //     item.attr_vals = item.attr_vals.split(' ')
        // });
        this.goodsAttr = res.data
        console.log(this.goodsAttr)
      }
    },
    // 级联选择器改变时触发的函数
    CateChange(arr) {
      if (this.selc_cateID.length < 3) {
        this.selc_cateID = []
        return
      }
    },
    // tab标签切换前触发的钩子函数
    beforeLeave(activeName, oldActiveName) {
      let res = false
      this.$refs.addForm.validate(valid => {
        if (!valid) {
          res = valid
          this.activeStep = '0'
          this.$message.error('商品信息还没有填写完整哦~')
          return
        }
        if (this.selc_cateID.length < 3) {
          this.$message.error('还没有选择商品分类哦~')
          return
        }
        res = true
      })
      if (!res) {
        return false
      }
    },
    // 文件上传成功的时候触发的钩子
    updateOK(response, file, fileList) {
      if (response.meta.status !== 200)
        return this.$message.error('图片上传失败~')
      this.addForm.pics.push({ pic: response.data.tmp_path })
      console.log(this.addForm.pics)
    },
    // 移除图片触发的函数
    removeFile(file, fileList) {
      this.addForm.pics = []
      fileList.forEach(item => {
        this.addForm.pics.push({ pic: item.response.data.tmp_path })
      })
      console.log(this.addForm.pics)
    },
    // 点击图片名称时触发的钩子
    previewPic(f) {
      this.previewVisible = true
      this.previewPath = f.response.data.url
    },
    // 图片预览关闭按钮处理函数
    previewClose() {
      this.previewVisible = false
    },
    // 添加商品按钮
    async addGoodsBtn() {
      if (!this.addForm.goods_introduce)
        return this.$message.error('还没有输入内容呢~ ↑')
      this.addForm.goods_cat = this.selc_cateID.join(',')
      this.goodsParams.forEach(item => {
        this.addForm.attrs.push({
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(' ')
        })
      })
      this.goodsAttr.forEach(item => {
        this.addForm.attrs.push({
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        })
      })
      const { data: res } = await this.$http.post('/goods', this.addForm)
      if (res.meta.status !== 201) {
        return this.$message.error('添加商品失败,请稍后再试~')
      }
      this.$message.success('添加商品成功~')
      this.$refs.addForm.resetFields()
      this.$router.push('/goods')
    }
  },
  created() {
    this.getCateList()
  },
  components: {
    'quill-editor': quillEditor
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin-top: 20px;
  margin-bottom: 20px;
}
.el-checkbox {
  margin-right: 10px;
  margin-bottom: 10px;
  margin-left: 0;
}

.preimg {
  width: 100%;
}

#editor {
  min-height: 350px;
}
.el-button {
  margin-top: 20px;
}
</style>